package elven.d.rabbitmq.server.util;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 生产者消费者队列通用类
 * @author elven
 */
public abstract class EndPoint {

	protected Channel channel;
	protected Connection connection;
	protected String endPointName;
	
	public EndPoint(String endPointName) throws TimeoutException, IOException {
		this.endPointName = endPointName;
		//构建连接
		connection = RabbitMQConnectionFactory.getConnectionFactory().newConnection();
		//创建消息通道
		channel = connection.createChannel();
		//声明一个消息队列(消息名称,是否持久化,是否为独立的,是否自动删除,参数)
		channel.queueDeclare(endPointName, false, false, false, null);
	}

	/**
	 * 关闭通道和连接并非必须的，因为隐含是自动调用的
	 * @throws IOException
	 * @throws TimeoutException 
	 */
	public void close() throws IOException, TimeoutException{
		this.channel.close();
		this.connection.close();
	}

	@Override
	public String toString() {
		return "EndPoint [channel=" + channel + ", connection=" + connection + ", endPointName=" + endPointName + "]";
	}
	
}
